package v1

import (
	"time"
	"wms/internal/model"
	"wms/internal/model/request"
	"wms/internal/model/response"
	"wms/pkg/common"
	"wms/pkg/global"
	"wms/pkg/logger"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// SystemLogController 系统日志控制器
type SystemLogController struct{}

// NewSystemLogController 创建系统日志控制器
func NewSystemLogController() *SystemLogController {
	return &SystemLogController{}
}

// GetLogList 获取系统日志列表
// GetLogList godoc
// @Summary 获取系统日志列表
// @Description 获取系统操作日志列表，支持分页和筛选
// @Tags 系统管理
// @Accept json
// @Produce json
// @Security Bearer
// @Param page query int false "页码" default(1)
// @Param pageSize query int false "每页数量" default(10)
// @Param type query string false "日志类型/操作类型"
// @Param keyword query string false "搜索关键词"
// @Param dateRange query []string false "日期范围，格式: ['2023-01-01', '2023-12-31']"
// @Success 200 {object} common.Response{data=[]response.LogResponse} "成功"
// @Failure 400 {object} common.Response "请求参数错误"
// @Failure 500 {object} common.Response "服务器内部错误"
// @Router /system/logs [get]
func (c *SystemLogController) GetLogList(ctx *gin.Context) {
	var req request.LogListRequest

	// 尝试绑定参数
	if err := ctx.ShouldBindQuery(&req); err != nil {
		logger.Warn("绑定日志列表请求参数失败", zap.Error(err))
		common.Error(ctx, err)
		return
	}

	// 设置默认值
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}

	logger.Info("开始获取系统日志列表",
		zap.Int("page", req.Page),
		zap.Int("pageSize", req.PageSize),
		zap.String("level", req.Type),
		zap.String("keyword", req.Keyword))

	// 构建查询
	db := global.DB.Model(&model.OperationLog{})

	// 添加筛选条件
	if req.Type != "" {
		db = db.Where("action = ?", req.Type)
	}

	if req.Keyword != "" {
		db = db.Where("username LIKE ? OR module LIKE ? OR path LIKE ? OR request_data LIKE ?",
			"%"+req.Keyword+"%", "%"+req.Keyword+"%", "%"+req.Keyword+"%", "%"+req.Keyword+"%")
	}

	// 处理日期范围
	if len(req.DateRange) == 2 && req.DateRange[0] != "" && req.DateRange[1] != "" {
		startTime, err1 := time.Parse("2006-01-02T15:04:05Z", req.DateRange[0])
		endTime, err2 := time.Parse("2006-01-02T15:04:05Z", req.DateRange[1])

		if err1 == nil && err2 == nil {
			db = db.Where("created_at BETWEEN ? AND ?", startTime, endTime)
		} else {
			// 尝试其他格式
			db = db.Where("created_at BETWEEN ? AND ?", req.DateRange[0], req.DateRange[1])
		}
	}

	// 获取总数
	var total int64
	if err := db.Count(&total).Error; err != nil {
		logger.Error("获取日志总数失败", zap.Error(err))
		common.Error(ctx, err)
		return
	}

	// 分页查询
	var logs []model.OperationLog
	offset := (req.Page - 1) * req.PageSize
	if err := db.Order("created_at DESC").Offset(offset).Limit(req.PageSize).Find(&logs).Error; err != nil {
		logger.Error("查询日志列表失败", zap.Error(err))
		common.Error(ctx, err)
		return
	}

	// 转换为响应格式
	var logResponses []response.LogResponse
	for _, log := range logs {
		logResponses = append(logResponses, response.LogResponse{
			ID:           log.ID,
			UserID:       log.UserID,
			Username:     log.Username,
			IP:           log.IP,
			Method:       log.Method,
			Path:         log.Path,
			Status:       log.Status,
			Type:         log.Action,
			Latency:      log.Duration,
			ErrorMsg:     log.Error,
			RequestBody:  log.RequestData,
			ResponseBody: log.Response,
			CreatedAt:    log.CreatedAt,
			Time:         log.CreatedAt.Format("2006-01-02 15:04:05"),
			Level:        lookupLogLevel(log.Status, log.Error),
			Message:      generateLogMessage(log),
			Caller:       log.Path,
			Operation:    log.Action,
		})
	}

	logger.Info("获取系统日志成功", zap.Int("count", len(logResponses)), zap.Int64("total", total))
	common.Success(ctx, gin.H{
		"list":  logResponses,
		"total": total,
		"page":  req.Page,
		"size":  req.PageSize,
	})
}

// lookupLogLevel 根据状态码和错误信息确定日志级别
func lookupLogLevel(status int, errorMsg string) string {
	if status >= 500 || errorMsg != "" {
		return "ERROR"
	}
	if status >= 400 {
		return "WARN"
	}
	return "INFO"
}

// generateLogMessage 生成日志消息
func generateLogMessage(log model.OperationLog) string {
	var msg string
	switch log.Action {
	case "登录":
		msg = "用户登录系统"
	case "退出":
		msg = "用户退出系统"
	case "查询":
		msg = "查询数据 - " + log.Module
	case "创建":
		msg = "创建数据 - " + log.Module
	case "更新":
		msg = "更新数据 - " + log.Module
	case "删除":
		msg = "删除数据 - " + log.Module
	default:
		if log.Method == "GET" {
			msg = "查询操作 - " + log.Path
		} else if log.Method == "POST" {
			msg = "创建操作 - " + log.Path
		} else if log.Method == "PUT" {
			msg = "更新操作 - " + log.Path
		} else if log.Method == "DELETE" {
			msg = "删除操作 - " + log.Path
		} else {
			msg = log.Method + " " + log.Path
		}
	}

	if log.Error != "" {
		msg += " - 错误: " + log.Error
	}

	return msg
}
